//
//  VideoViewController.m
//  SelfDriving
//
//  Created by apple on 16/2/3.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "VideoViewController.h"
#import "EditImageController.h"
#import <AVFoundation/AVFoundation.h>
#import "VideoCompleteVC.h"
#import "ZLPhotoPickerGroup.h"

typedef NS_ENUM(NSInteger,VideoStatus){
    VideoStatusEnded = 0,
    VideoStatusStarted
};
@interface VideoViewController ()<AVCaptureFileOutputRecordingDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property ( strong , nonatomic ) AVCaptureDevice * device;
@property ( strong , nonatomic ) AVCaptureDeviceInput * input;
@property ( strong , nonatomic ) AVCaptureMovieFileOutput * output;
@property ( strong , nonatomic ) AVCaptureStillImageOutput * outputimg;
@property ( strong , nonatomic ) AVCaptureSession * session;
@property (weak, nonatomic) IBOutlet UIView *titleView;
@property ( strong , nonatomic ) AVCaptureVideoPreviewLayer * preview;
@property (strong, nonatomic) UIImageView *scanLayer;
@property (strong,nonatomic)UIImagePickerController * imagePikerViewController;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UIButton *completeBtn;
@property (weak, nonatomic) IBOutlet UILabel *shotTime;
@property (weak, nonatomic) IBOutlet UILabel *totalTime;
@property (weak, nonatomic) IBOutlet UIButton *sanguangBtn;
@property (weak, nonatomic) IBOutlet UIButton *qiehuanBtn;
@property (weak, nonatomic) IBOutlet UIView *videoView;
@property (weak, nonatomic) IBOutlet UIProgressView *progress;
@property (nonatomic,weak) UIView *focusCircle;
@property (nonatomic,assign) VideoStatus status;
@property (nonatomic,assign) BOOL canSave;
@property (nonatomic,strong) CADisplayLink *link;
@property (nonatomic,strong)NSTimer *countTimer;
@property (nonatomic,strong) NSMutableArray *groupArrays;
@property (nonatomic,strong) NSMutableArray *videoList;
@property (weak, nonatomic) IBOutlet UIImageView *imgView;
@property (weak, nonatomic) IBOutlet UIButton *zpBtn;
@property (weak, nonatomic) IBOutlet UIButton *spBtn;
@property (weak, nonatomic) IBOutlet UIButton *CaptureBtn;
@property (weak, nonatomic) IBOutlet UIView *xiaView;
@property (weak, nonatomic) IBOutlet UIButton *tsu;
@property (weak, nonatomic) IBOutlet UIButton *xcBtn;

@end

@implementation VideoViewController{
    AVCaptureSession *_captureSession;
    AVCaptureDevice *_videoDevice;
    AVCaptureDevice *_audioDevice;
    AVCaptureDeviceInput *_videoInput;
    AVCaptureDeviceInput *_audioInput;
    AVCaptureMovieFileOutput *_movieOutput;
    AVCaptureVideoPreviewLayer *_captureVideoPreviewLayer;
    int totaTime;
    NSThread *thread;
    
    NSData *videoData;
    
    int seconds;
    int minus;
    BOOL iszpsp;
    
    NSMutableArray *tmpimagedata;
    NSString *imgurl;//图库下一步图片路径
    
    UIImage *saveImage;

}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
    //UIStatusBarStyleDefault = 0 黑色文字，浅色背景时使用
    //UIStatusBarStyleLightContent = 1 白色文字，深色背景时使用
}
- (BOOL)prefersStatusBarHidden
{
    return YES; //返回NO表示要显示，返回YES将hiden
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNeedsStatusBarAppearanceUpdate];
    
    [QMUITips showInfo:@"请用竖屏拍摄！" inView:self.view hideAfterDelay:1.5];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(viewwiliship:)
     name:@"viewwiliship"
     object:nil];
    
    totaTime = 0;
    
    _videoList = [[NSMutableArray alloc]init];
    _groupArrays = [[NSMutableArray alloc]init];
    
    //    _totalTime.text = [NSString stringWithFormat:@"%d秒",totaTime];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(backAction:)
     name:@"backAction"
     object:nil];
    // 创建
    [self getAuthorization];
    [self addGenstureRecognizer];
    
    UISwipeGestureRecognizer* gestureSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(qiehuanzpsp:)];
    gestureSwipe.direction = UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft;
    [_xiaView addGestureRecognizer:gestureSwipe];
    [self.view addGestureRecognizer:gestureSwipe];
    _xiaView.backgroundColor = [UIColor clearColor];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(initview:)
     name:@"initview"
     object:nil];
    [self initview];

    
}
#pragma mark 刷新视频UI
-(void)viewwiliship:(UIButton *)btn{
    [self getAuthorization];
    [self addGenstureRecognizer];
}
//获取授权
- (void)getAuthorization
{
    /*
     AVAuthorizationStatusNotDetermined = 0,// 未进行授权选择
     
     AVAuthorizationStatusRestricted,　　　　// 未授权，且用户无法更新，如家长控制情况下
     
     AVAuthorizationStatusDenied,　　　　　　 // 用户拒绝App使用
     
     AVAuthorizationStatusAuthorized,　　　　// 已授权，可使用
     */
    //此处获取摄像头授权
    switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo])
    {
        case AVAuthorizationStatusAuthorized:       //已授权，可使用    The client is authorized to access the hardware supporting a media type.
        {
            NSLog(@"授权摄像头使用成功");
            [self setupAVCaptureInfo];
            break;
        }
        case AVAuthorizationStatusNotDetermined:    //未进行授权选择     Indicates that the user has not yet made a choice regarding whether the client can access the hardware.
        {
            //则再次请求授权
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                if(granted){    //用户授权成功
                    [self setupAVCaptureInfo];
                    return;
                } else {        //用户拒绝授权
                    [self pop];
                    [self showMsgWithTitle:@"出错了" andContent:@"用户拒绝授权摄像头的使用权,返回上一页.请打开\n设置-->隐私/通用等权限设置"];
                    return;
                }
            }];
            break;
        }
        default:                                    //用户拒绝授权/未授权
        {
            [self pop];
            [self showMsgWithTitle:@"出错了" andContent:@"拒绝授权,返回上一页.请检查下\n设置-->隐私/通用等权限设置"];
            break;
        }
    }
    
}

- (void)setupAVCaptureInfo
{
    [self addSession];
    
    [_captureSession beginConfiguration];
    
    [self addVideo];
    [self addAudio];
    [self addPreviewLayer];
    
    [_captureSession commitConfiguration];
    
    //开启会话-->注意,不等于开始录制
    [_captureSession startRunning];
    
}

- (void)addSession
{
    _captureSession = [[AVCaptureSession alloc] init];
    [ _captureSession setSessionPreset : AVCaptureSessionPresetHigh ];
    //设置视频分辨率
    /*  通常支持如下格式
     (
     AVAssetExportPresetLowQuality,
     AVAssetExportPreset960x540,
     AVAssetExportPreset640x480,
     AVAssetExportPresetMediumQuality,
     AVAssetExportPreset1920x1080,
     AVAssetExportPreset1280x720,
     AVAssetExportPresetHighestQuality,
     AVAssetExportPresetAppleM4A
     )
     */
    //注意,这个地方设置的模式/分辨率大小将影响你后面拍摄照片/视频的大小,
    if ([_captureSession canSetSessionPreset:AVCaptureSessionPreset640x480]) {
        [_captureSession setSessionPreset:AVCaptureSessionPreset640x480];
    }
    _outputimg = [[AVCaptureStillImageOutput alloc] init];
//    NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
    NSDictionary *outputSettings = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedInt:kCVPixelFormatType_32BGRA], (id)kCVPixelBufferPixelFormatTypeKey, nil];
 
    //这是输出流的设置参数AVVideoCodecJPEG参数表示以JPEG的图片格式输出图片
    [_outputimg setOutputSettings:outputSettings];
    if ([ _captureSession canAddOutput : _outputimg ])
    {
        [ _captureSession addOutput : _outputimg ];
    }
}

- (void)addVideo
{
    // 获取摄像头输入设备， 创建 AVCaptureDeviceInput 对象
    /* MediaType
     AVF_EXPORT NSString *const AVMediaTypeVideo                 NS_AVAILABLE(10_7, 4_0);       //视频
     AVF_EXPORT NSString *const AVMediaTypeAudio                 NS_AVAILABLE(10_7, 4_0);       //音频
     AVF_EXPORT NSString *const AVMediaTypeText                  NS_AVAILABLE(10_7, 4_0);
     AVF_EXPORT NSString *const AVMediaTypeClosedCaption         NS_AVAILABLE(10_7, 4_0);
     AVF_EXPORT NSString *const AVMediaTypeSubtitle              NS_AVAILABLE(10_7, 4_0);
     AVF_EXPORT NSString *const AVMediaTypeTimecode              NS_AVAILABLE(10_7, 4_0);
     AVF_EXPORT NSString *const AVMediaTypeMetadata              NS_AVAILABLE(10_8, 6_0);
     AVF_EXPORT NSString *const AVMediaTypeMuxed                 NS_AVAILABLE(10_7, 4_0);
     */
    
    /* AVCaptureDevicePosition
     typedef NS_ENUM(NSInteger, AVCaptureDevicePosition) {
     AVCaptureDevicePositionUnspecified         = 0,
     AVCaptureDevicePositionBack                = 1,            //后置摄像头
     AVCaptureDevicePositionFront               = 2             //前置摄像头
     } NS_AVAILABLE(10_7, 4_0) __TVOS_PROHIBITED;
     */
    
    
    
    AVCaptureDevicePosition position = [[[NSUserDefaults standardUserDefaults]objectForKey:@"qiehuan"] intValue];
    
    _videoDevice = [self deviceWithMediaType:AVMediaTypeVideo preferringPosition:position];
    [_videoDevice setFlashMode:AVCaptureFlashModeOff];
    [_videoDevice setTorchMode:AVCaptureTorchModeOff];
    
    
    [self addVideoInput];
    [self addMovieOutput];

}

- (void)addVideoInput
{
    NSError *videoError;
    
    // 视频输入对象
    // 根据输入设备初始化输入对象，用户获取输入数据
    _videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:_videoDevice error:&videoError];
    if (videoError) {
        NSLog(@"---- 取得摄像头设备时出错 ------ %@",videoError);
        return;
    }
    
    // 将视频输入对象添加到会话 (AVCaptureSession) 中
    if ([_captureSession canAddInput:_videoInput]) {
        [_captureSession addInput:_videoInput];
    }
    
}

- (void)addMovieOutput
{
    // 拍摄视频输出对象
    // 初始化输出设备对象，用户获取输出数据
    _movieOutput = [[AVCaptureMovieFileOutput alloc] init];
    
    if ([_captureSession canAddOutput:_movieOutput]) {
        [_captureSession addOutput:_movieOutput];
        AVCaptureConnection *captureConnection = [_movieOutput connectionWithMediaType:AVMediaTypeVideo];
        
        //设置视频旋转方向
        /*
         typedef NS_ENUM(NSInteger, AVCaptureVideoOrientation) {
         AVCaptureVideoOrientationPortrait           = 1,
         AVCaptureVideoOrientationPortraitUpsideDown = 2,
         AVCaptureVideoOrientationLandscapeRight     = 3,
         AVCaptureVideoOrientationLandscapeLeft      = 4,
         } NS_AVAILABLE(10_7, 4_0) __TVOS_PROHIBITED;
         */
        //        if ([captureConnection isVideoOrientationSupported]) {
        //            [captureConnection setVideoOrientation:AVCaptureVideoOrientationPortrait];
        //        }
        
        // 视频稳定设置
        if ([captureConnection isVideoStabilizationSupported]) {
            captureConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
        }
        captureConnection.videoScaleAndCropFactor = captureConnection.videoMaxScaleAndCropFactor;
    }
    
}

- (void)addAudio
{
    NSError *audioError;
    // 添加一个音频输入设备
    _audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    //  音频输入对象
    _audioInput = [[AVCaptureDeviceInput alloc] initWithDevice:_audioDevice error:&audioError];
    if (audioError) {
        NSLog(@"取得录音设备时出错 ------ %@",audioError);
        return;
    }
    // 将音频输入对象添加到会话 (AVCaptureSession) 中
    if ([_captureSession canAddInput:_audioInput]) {
        [_captureSession addInput:_audioInput];
    }
}

- (void)addPreviewLayer
{
    
    [self.view layoutIfNeeded];
    
    // 通过会话 (AVCaptureSession) 创建预览层
    _captureVideoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_captureSession];
    _captureVideoPreviewLayer.frame = CGRectMake(0, 0, SCRE_WIDTH, _videoView.frame.size.height);
    /* 填充模式
     Options are AVLayerVideoGravityResize, AVLayerVideoGravityResizeAspect and AVLayerVideoGravityResizeAspectFill. AVLayerVideoGravityResizeAspect is default.
     */
    //有时候需要拍摄完整屏幕大小的时候可以修改这个
    _captureVideoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    // 如果预览图层和视频方向不一致,可以修改这个
    //    _captureVideoPreviewLayer.connection.videoOrientation = [_movieOutput connectionWithMediaType:AVMediaTypeVideo].videoOrientation;
    //    _captureVideoPreviewLayer.position = CGPointMake(self.view.frame.size.width*0.5,self.view.frame.size.height*0.5);
    // 显示在视图表面的图层
    [_videoView.layer addSublayer:_captureVideoPreviewLayer];
}

#pragma mark pop

-(void)pop
{
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
#pragma mark --- 谢威
    [self dismissViewControllerAnimated:YES completion:nil];
    
    
}

- (void)showMsgWithTitle:(NSString *)title andContent:(NSString *)content
{
    [[[UIAlertView alloc] initWithTitle:title message:content delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] show];
}

#pragma mark 获取摄像头-->前/后

- (AVCaptureDevice *)deviceWithMediaType:(NSString *)mediaType preferringPosition:(AVCaptureDevicePosition)position
{
    
    
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:mediaType];
    AVCaptureDevice *captureDevice = devices.firstObject;
    
    for ( AVCaptureDevice *device in devices ) {
        if ( device.position == position ) {
            captureDevice = device;
            break;
        }
    }
    
    return captureDevice;
}
/**
 *  添加点按手势，点按时聚焦
 */
-(void)addGenstureRecognizer{
    
    UITapGestureRecognizer *singleTapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleTap:)];
    singleTapGesture.numberOfTapsRequired = 1;
    singleTapGesture.delaysTouchesBegan = YES;
    
    UITapGestureRecognizer *doubleTapGesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTap:)];
    doubleTapGesture.numberOfTapsRequired = 2;
    doubleTapGesture.delaysTouchesBegan = YES;
    
    [singleTapGesture requireGestureRecognizerToFail:doubleTapGesture];
    [self.videoView addGestureRecognizer:singleTapGesture];
    [self.videoView addGestureRecognizer:doubleTapGesture];
}

-(void)singleTap:(UITapGestureRecognizer *)tapGesture{
    
    NSLog(@"单击");
    
    CGPoint point= [tapGesture locationInView:self.videoView];
    //将UI坐标转化为摄像头坐标,摄像头聚焦点范围0~1
    [self setFocusCursorAnimationWithPoint:point];

    CGPoint cameraPoint= [_captureVideoPreviewLayer captureDevicePointOfInterestForPoint:point];
    
    [self changeDevicePropertySafety:^(AVCaptureDevice *captureDevice) {
        
        /*
         @constant AVCaptureFocusModeLocked 锁定在当前焦距
         Indicates that the focus should be locked at the lens' current position.
         
         @constant AVCaptureFocusModeAutoFocus 自动对焦一次,然后切换到焦距锁定
         Indicates that the device should autofocus once and then change the focus mode to AVCaptureFocusModeLocked.
         
         @constant AVCaptureFocusModeContinuousAutoFocus 当需要时.自动调整焦距
         Indicates that the device should automatically focus when needed.
         */
        //聚焦
        if ([captureDevice isFocusModeSupported:AVCaptureFocusModeContinuousAutoFocus]) {
            [captureDevice setFocusMode:AVCaptureFocusModeContinuousAutoFocus];
            NSLog(@"聚焦模式修改为%zd",AVCaptureFocusModeContinuousAutoFocus);
        }else{
            NSLog(@"聚焦模式修改失败");
        }
        
        //聚焦点的位置
        if ([captureDevice isFocusPointOfInterestSupported]) {
            [captureDevice setFocusPointOfInterest:cameraPoint];
        }
        
        /*
         @constant AVCaptureExposureModeLocked  曝光锁定在当前值
         Indicates that the exposure should be locked at its current value.
         
         @constant AVCaptureExposureModeAutoExpose 曝光自动调整一次然后锁定
         Indicates that the device should automatically adjust exposure once and then change the exposure mode to AVCaptureExposureModeLocked.
         
         @constant AVCaptureExposureModeContinuousAutoExposure 曝光自动调整
         Indicates that the device should automatically adjust exposure when needed.
         
         @constant AVCaptureExposureModeCustom 曝光只根据设定的值来
         Indicates that the device should only adjust exposure according to user provided ISO, exposureDuration values.
         
         */
        //曝光模式
        if ([captureDevice isExposureModeSupported:AVCaptureExposureModeAutoExpose]) {
            [captureDevice setExposureMode:AVCaptureExposureModeAutoExpose];
        }else{
            NSLog(@"曝光模式修改失败");
        }
        
        //曝光点的位置
        if ([captureDevice isExposurePointOfInterestSupported]) {
            [captureDevice setExposurePointOfInterest:cameraPoint];
        }
    }];
}
//设置焦距
-(void)doubleTap:(UITapGestureRecognizer *)tapGesture{
    
    NSLog(@"双击");
    [self changeDevicePropertySafety:^(AVCaptureDevice *captureDevice) {
        if (captureDevice.videoZoomFactor == 1.0) {
            CGFloat current = 1.5;
            if (current < captureDevice.activeFormat.videoMaxZoomFactor) {
                [captureDevice rampToVideoZoomFactor:current withRate:10];
            }
        }else{
            [captureDevice rampToVideoZoomFactor:1.0 withRate:10];
        }
    }];
}

//光圈动画
-(void)setFocusCursorAnimationWithPoint:(CGPoint)point{
    self.focusCircle.center = point;
    self.focusCircle.transform = CGAffineTransformIdentity;
    self.focusCircle.alpha = 1.0;
    [UIView animateWithDuration:0.5 animations:^{
        self.focusCircle.transform=CGAffineTransformMakeScale(0.5, 0.5);
        self.focusCircle.alpha = 0.0;
    }];
}

//光圈
- (UIView *)focusCircle{
    if (!_focusCircle) {
        UIView *focusCircle = [[UIView alloc] init];
        focusCircle.frame = CGRectMake(0, 0, 100, 100);
        focusCircle.layer.borderColor = [UIColor orangeColor].CGColor;
        focusCircle.layer.borderWidth = 2;
        focusCircle.layer.cornerRadius = 50;
        focusCircle.layer.masksToBounds =YES;
        _focusCircle = focusCircle;
        [self.videoView addSubview:focusCircle];
    }
    return _focusCircle;
}





- (IBAction)qiehuanAction:(UIButton *)sender {
    switch (_videoDevice.position) {
        case AVCaptureDevicePositionBack:
            _videoDevice = [self deviceWithMediaType:AVMediaTypeVideo preferringPosition:AVCaptureDevicePositionFront];
            [[NSUserDefaults standardUserDefaults]setObject:@2 forKey:@"qiehuan"];
            break;
        case AVCaptureDevicePositionFront:
            _videoDevice = [self deviceWithMediaType:AVMediaTypeVideo preferringPosition:AVCaptureDevicePositionBack];
            [[NSUserDefaults standardUserDefaults]setObject:@1 forKey:@"qiehuan"];
            break;
        default:
            return;
            break;
    }
    
    [self changeDevicePropertySafety:^(AVCaptureDevice *captureDevice) {
        NSError *error;
        AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:_videoDevice error:&error];
        
        if (newVideoInput != nil) {
            //必选先 remove 才能询问 canAdd
            [_captureSession removeInput:_videoInput];
            if ([_captureSession canAddInput:newVideoInput]) {
                [_captureSession addInput:newVideoInput];
                _videoInput = newVideoInput;
            }else{
                [_captureSession addInput:_videoInput];
            }
            
        } else if (error) {
            NSLog(@"切换前/后摄像头失败, error = %@", error);
        }
    }];
    
    
}
- (IBAction)shanguangAction:(UIButton *)sender {
    BOOL con1 = [_videoDevice hasTorch];    //支持手电筒模式
    BOOL con2 = [_videoDevice hasFlash];    //支持闪光模式
    
    if (con1 && con2)
    {
        [self changeDevicePropertySafety:^(AVCaptureDevice *captureDevice) {
            if (_videoDevice.flashMode == AVCaptureFlashModeOn)         //闪光灯开
            {
                [_videoDevice setFlashMode:AVCaptureFlashModeOff];
                [_videoDevice setTorchMode:AVCaptureTorchModeOff];
            }else if (_videoDevice.flashMode == AVCaptureFlashModeOff)  //闪光灯关
            {
                [_videoDevice setFlashMode:AVCaptureFlashModeOn];
                [_videoDevice setTorchMode:AVCaptureTorchModeOn];
            }
            //            else{                                                      //闪光灯自动
            //                [_videoDevice setFlashMode:AVCaptureFlashModeAuto];
            //                [_videoDevice setTorchMode:AVCaptureTorchModeAuto];
            //            }
            NSLog(@"现在的闪光模式是AVCaptureFlashModeOn么?是你就扣1, %zd",_videoDevice.flashMode == AVCaptureFlashModeOn);
        }];
        sender.selected=!sender.isSelected;
    }else{
        NSLog(@"不能切换闪光模式");
    }
}
#pragma  mark 拍照
- (IBAction)StartShootingAction:(UIButton *)sender {
    if (iszpsp) {
        return;
    }
    AVCaptureConnection * videoConnection = [_outputimg connectionWithMediaType:AVMediaTypeVideo];
    if (!videoConnection) {
        NSLog(@"take photo failed!");
        return;
    }
    [self.outputimg captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
        if (imageDataSampleBuffer == NULL) {
            return;
        }
        UIImage *image = [self imageFromSampleBuffer:imageDataSampleBuffer];
       
        
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        
        [UserDefaults writeUserDefaultObjectValue:@"0" withKey:@"isship"];
        NSLog(@"image size = %@",NSStringFromCGSize(image.size));
        
    }];

}
#pragma  mark 保存图片至相册回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error == nil) {
        
        image = [UIImage fixOrientation:image];
        
        NSLog(@"contentinfo %@",contextInfo);
        EditImageController *editImageController = [[EditImageController alloc]init];
        editImageController.image = image;
        [self presentViewController:editImageController animated:NO completion:nil];
        
    }else{
        [SVProgressHUD showImage:nil status:error.description];
    }
}


// Create a UIImage from sample buffer data
- (UIImage *) imageFromSampleBuffer:(CMSampleBufferRef) sampleBuffer
{
    // 为媒体数据设置一个CMSampleBuffer的Core Video图像缓存对象
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    // 锁定pixel buffer的基地址
    CVPixelBufferLockBaseAddress(imageBuffer, 0);
    
    // 得到pixel buffer的基地址
    void *baseAddress = CVPixelBufferGetBaseAddress(imageBuffer);
    
    // 得到pixel buffer的行字节数
    size_t bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer);
    // 得到pixel buffer的宽和高
    size_t width = CVPixelBufferGetWidth(imageBuffer);
    size_t height = CVPixelBufferGetHeight(imageBuffer);
    
    //NSLog(@"%zu,%zu",width,height);
    
    // 创建一个依赖于设备的RGB颜色空间
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    // 用抽样缓存的数据创建一个位图格式的图形上下文（graphics context）对象
    CGContextRef context = CGBitmapContextCreate(baseAddress, width, height, 8,
                                                 bytesPerRow, colorSpace, kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst);
    
    
    // 根据这个位图context中的像素数据创建一个Quartz image对象
    CGImageRef quartzImage = CGBitmapContextCreateImage(context);
    // 解锁pixel buffer
    CVPixelBufferUnlockBaseAddress(imageBuffer,0);
    
    // 释放context和颜色空间
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    
    //    cgimageget`
    
    // 用Quartz image创建一个UIImage对象image
    //UIImage *image = [UIImage imageWithCGImage:quartzImage];
    UIImage *image = [UIImage imageWithCGImage:quartzImage scale:1.0f orientation:UIImageOrientationRight];
    
    // 释放Quartz image对象
    CGImageRelease(quartzImage);
    
    return (image);
}
-(void)initview:(NSNotification *)not{
    [self initview];
}
 
-(void)viewWillAppear:(BOOL)animated{
    if([AppDelegate shareDelegate].Close){
        [self dismissViewControllerAnimated:NO completion:nil];
        [AppDelegate shareDelegate].Close = NO;
    }
//    [self initview];
   
}
-(void)initview{
    self.navigationController.navigationBarHidden  = YES;
    if([[UserDefaults readUserDefaultObjectValueForKey:@"isship"] intValue] == 1){//视频
        _titleView.hidden = NO;
        _tsu.hidden = YES;
        _xiaView.hidden = NO;
        _spBtn.selected = YES;
        _zpBtn.selected = NO;
        _xcBtn.hidden = NO;
        [_CaptureBtn setImage:[UIImage imageNamed:@"psspbtn"] forState:UIControlStateNormal];
        iszpsp = YES;
        //button长按事件
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(kaishipaisAction:)];
        [_CaptureBtn addGestureRecognizer:longPress];
        [_xcBtn setImage:[UIImage imageNamed:@"pzsptb"] forState:UIControlStateNormal];
    }else{
        _titleView.hidden = NO;
        _tsu.hidden = YES;
        _xiaView.hidden = NO;
        _spBtn.selected = NO;
        _zpBtn.selected = YES;
        _xcBtn.hidden = YES;
        [_CaptureBtn setImage:[UIImage imageNamed:@"kpzpbtn"] forState:UIControlStateNormal];
        iszpsp = NO;
        [_xcBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    }
  
    
}
#pragma mark 获取本地视频或照片
- (IBAction)xcAction:(UIButton *)sender {
    if(!iszpsp){
        ZLPhotoPickerViewController *pickerVc = [[ZLPhotoPickerViewController alloc] init];
        pickerVc.maxCount = 1;
        pickerVc.status = PickerViewShowStatusCameraRoll;
        pickerVc.callBack = ^(NSArray *status){
            ZLPhotoAssets *zlc = [status firstObject];
            EditImageController *editImageController = [[EditImageController alloc]init];
            editImageController.image = [zlc originImage];
            [self dismissViewControllerAnimated:NO completion:nil];
            [self presentViewController:editImageController animated:YES completion:nil];
            [UserDefaults writeUserDefaultObjectValue:@"0" withKey:@"isship"];
            
        };
        [pickerVc showPickerVc:self];
    }else{
        [UserDefaults writeUserDefaultObjectValue:@"isship" withKey:@"1"];
        ZLPhotoPickerViewController *pickerVc = [[ZLPhotoPickerViewController alloc] init];
        pickerVc.maxCount = 1;
        pickerVc.status = PickerViewShowStatusVideo;
        pickerVc.callBack = ^(NSArray *status){
             ZLPhotoAssets *photo = [status firstObject];
            UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"KP"
                                                                         bundle:[NSBundle mainBundle]];
            VideoCompleteVC *viewcv = [customerStoryboard instantiateViewControllerWithIdentifier:@"VideoCompleteVC"];
            viewcv.videoUrl = photo.assetURL;
            viewcv.data = _videoList;
            viewcv.modalPresentationStyle= UIModalPresentationOverFullScreen;
            [self dismissViewControllerAnimated:NO completion:nil];
            [self presentViewController:viewcv animated:YES completion:nil];

        };
        [pickerVc showPickerVc:self];
        
    }
}
#pragma mark 滑动照片或者视频
-(void)qiehuanzpsp:(UIGestureRecognizer *)cgr{
    [UIView animateWithDuration:0.7 animations:^{
        _videoView.alpha = 0.3;        // 毛玻璃底的imageview
        _videoView.alpha = 1;    // 高清deimageview
    }completion:^(BOOL finish) {
     }];
    _imgView.hidden = YES;
    _xcBtn.hidden = YES;
    iszpsp = !iszpsp;
    if (iszpsp) {//视频
        _imgView.hidden = NO;
        _xcBtn.hidden = NO;
        [UIView animateWithDuration:0.7 animations:^{
         CGRect s =  _spBtn.frame;
            s.origin.x = SCRE_WIDTH/2-15;
            _spBtn.frame = s;
            
            CGRect z =  _zpBtn.frame;
            z.origin.x = -15;
            _zpBtn.frame = z;
            
        }completion:^(BOOL finish) {
        }];
        
        _spBtn.selected = YES;
        _zpBtn.selected = NO;
        [_CaptureBtn setImage:[UIImage imageNamed:@"psspbtn"] forState:UIControlStateNormal];
        [_xcBtn setImage:[UIImage imageNamed:@"pzsptb"] forState:UIControlStateNormal];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(kaishipaisAction:)];
        [_CaptureBtn addGestureRecognizer:longPress];
        
    }else{
        [UIView animateWithDuration:0.7 animations:^{
            CGRect s =  _spBtn.frame;
            s.origin.x = SCRE_WIDTH/2+15;
            _spBtn.frame = s;
            
            CGRect z =  _zpBtn.frame;
            z.origin.x = 15;
            _zpBtn.frame = z;
        }completion:^(BOOL finish) {
        }];
        _spBtn.selected = NO;
        _zpBtn.selected = YES;
        [_CaptureBtn setImage:[UIImage imageNamed:@"kpzpbtn"] forState:UIControlStateNormal];
        [_xcBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    }
    if (iszpsp) {
        _imgView.image = [AppDelegate shareDelegate].Videoimg;
    }else{
        _imgView.image = [AppDelegate shareDelegate].photoimg;
    }
}
- (IBAction)qieAction:(id)sender {
    [UIView animateWithDuration:0.7 animations:^{
        _videoView.alpha = 0.3;        // 毛玻璃底的imageview
        _videoView.alpha = 1;    // 高清deimageview
    }completion:^(BOOL finish) {
    }];
    _imgView.hidden = YES;
    _xcBtn.hidden = YES;
    iszpsp = !iszpsp;
    if (iszpsp) {
        _imgView.hidden = NO;
        _xcBtn.hidden = NO;
        [UIView animateWithDuration:0.7 animations:^{
            CGRect s =  _spBtn.frame;
            s.origin.x = SCRE_WIDTH/2-15;
            _spBtn.frame = s;
            
            CGRect z =  _zpBtn.frame;
            z.origin.x = -15;
            _zpBtn.frame = z;
            
        }completion:^(BOOL finish) {
        }];
        _spBtn.selected = YES;
        _zpBtn.selected = NO;
        [_CaptureBtn setImage:[UIImage imageNamed:@"psspbtn"] forState:UIControlStateNormal];
        [_xcBtn setImage:[UIImage imageNamed:@"pzsptb"] forState:UIControlStateNormal];
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(kaishipaisAction:)];
        [_CaptureBtn addGestureRecognizer:longPress];
        
    }else{
        [UIView animateWithDuration:0.7 animations:^{
            CGRect s =  _spBtn.frame;
            s.origin.x = SCRE_WIDTH/2+15;
            _spBtn.frame = s;
            
            CGRect z =  _zpBtn.frame;
            z.origin.x = 15;
            _zpBtn.frame = z;
        }completion:^(BOOL finish) {
        }];
        _spBtn.selected = NO;
        _zpBtn.selected = YES;
        [_CaptureBtn setImage:[UIImage imageNamed:@"kpzpbtn"] forState:UIControlStateNormal];
        [_xcBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    }
    if (iszpsp) {
        _imgView.image = [AppDelegate shareDelegate].Videoimg;
    }else{
        _imgView.image = [AppDelegate shareDelegate].photoimg;
    }
    
    
}




#pragma  mark （按住开始拍摄）
- (void)kaishipaisAction:(UIGestureRecognizer *)sender {
    
    if(sender.state == UIGestureRecognizerStateBegan){
        _shotTime.hidden = NO;
        _titleView.hidden = YES;
        _xiaView.hidden = YES;
        if (self.status == VideoStatusEnded) {
            self.status = VideoStatusStarted;
            [self startRecord];
            _shotTime.text = [NSString stringWithFormat:@"%02d:%02d:%02d",00,00,00];
            self.countTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(refresh) userInfo:nil repeats:YES];
        }
    }
    if(sender.state == UIGestureRecognizerStateEnded){
        [self recordComplete];
        [self stopAnimation];
    }
}

#pragma  mark 完成拍摄
- (IBAction)completeAction:(UIButton *)sender {
    [self recordComplete];
    [self stopAnimation];
    _titleView.hidden = NO;
    
}
#pragma  mark 取消拍摄
- (IBAction)cancelAction:(UIButton *)sender {
    [self stopRecord];
    [self stopAnimation];
    self.canSave = NO;
}
- (void)stopAnimation{
    _shotTime.hidden = YES;
    [_countTimer invalidate];
    totaTime = 0;
    if (self.status == VideoStatusStarted) {
        self.status = VideoStatusEnded;
        [self stopRecord];
    }
}
- (void)refresh{
    totaTime ++ ;
    if(seconds == 60){//时
        minus++;
        seconds = 0;
    }
    if (totaTime == 60) {//分
        seconds++;
        totaTime = 0;
    }
    [_tsu setTitle:@"⦁" forState:UIControlStateNormal];
    //    ／／让不断变量的时间数据进行显示到label上面。
    _shotTime.text = [NSString stringWithFormat:@"%02d:%02d.%02d",minus,seconds,totaTime];
}
#pragma mark 录制相关
- (NSURL *)outPutFileURL
{
    return [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), @"outPut.mov"]];
}

- (void)startRecord
{
    [_movieOutput startRecordingToOutputFileURL:[self outPutFileURL] recordingDelegate:self];
}

- (void)stopRecord
{
    // 取消视频拍摄
    [_movieOutput stopRecording];
}

- (void)recordComplete
{
    self.canSave = YES;
}

//这个在完全退出小视频时调用
- (void)quit
{
    [_captureSession stopRunning];
}

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didStartRecordingToOutputFileAtURL:(NSURL *)fileURL fromConnections:(NSArray *)connections
{
    NSLog(@"---- 开始录制 ----");
}

- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
    if (outputFileURL.absoluteString.length == 0 && captureOutput.outputFileURL.absoluteString.length == 0 ) {
        [self showMsgWithTitle:@"出错了" andContent:@"录制视频保存地址出错"];
        return;
    }
    
//    UISaveVideoAtPathToSavedPhotosAlbum([NSString stringWithFormat:@"%@",outputFileURL], nil, nil, nil);
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library writeVideoAtPathToSavedPhotosAlbum:outputFileURL
                                completionBlock:^(NSURL *assetURL, NSError *error) {
                                    if (error) {
                                        NSLog(@"Save video fail:%@",error);
                                    } else {
                                        NSLog(@"Save video succeed.");
                                    }
                                }];

    if (self.canSave) {
        [UserDefaults writeUserDefaultObjectValue:@"1" withKey:@"isship"];
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"KP"
                                                                     bundle:[NSBundle mainBundle]];
        VideoCompleteVC *viewcv = [customerStoryboard instantiateViewControllerWithIdentifier:@"VideoCompleteVC"];
        viewcv.videoUrl = outputFileURL;
        viewcv.data = _videoList;
        viewcv.modalPresentationStyle= UIModalPresentationOverFullScreen;
        [self presentViewController:viewcv animated:YES completion:nil];
         //        EditImageController *editImageController = [[EditImageController alloc]init];
        //        editImageController.image = _videoList;
        //        [self.navigationController pushViewController:editImageController animated:YES];
        self.canSave = NO;
    }
}
//更改设备属性前一定要锁上
-(void)changeDevicePropertySafety:(void (^)(AVCaptureDevice *captureDevice))propertyChange{
    //也可以直接用_videoDevice,但是下面这种更好
    AVCaptureDevice *captureDevice= [_videoInput device];
    NSError *error;
    //注意改变设备属性前一定要首先调用lockForConfiguration:调用完之后使用unlockForConfiguration方法解锁,意义是---进行修改期间,先锁定,防止多处同时修改
    BOOL lockAcquired = [captureDevice lockForConfiguration:&error];
    if (!lockAcquired) {
        NSLog(@"锁定设备过程error，错误信息：%@",error.localizedDescription);
    }else{
        [_captureSession beginConfiguration];
        propertyChange(captureDevice);
        [captureDevice unlockForConfiguration];
        [_captureSession commitConfiguration];
    }
}
- (IBAction)backAction:(UIButton *)sender {
    [self dismissViewControllerAnimated:NO completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
